<template>
  <div class="sign-result-page">
    <!-- 顶部培训班信息 -->
    <div class="top-info">
      <span class="class-id">培训班编号：{{ trainingClassCode }}</span>
      <span class="class-name">培训班名称：{{ trainingClassName }}</span>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area" v-if="showSearch">
      <el-form inline :model="searchForm" class="search-form" @submit.prevent="handleSearch">
        <el-form-item label="姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入姓名"
            class="search-input"
            @keyup.enter.native="handleSearch"
          />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号码"
            class="search-input"
            @keyup.enter.native="handleSearch"
            maxlength="11"
          />
        </el-form-item>
        <el-form-item label="证件编号">
          <el-input
            v-model="searchForm.idCard"
            placeholder="请输入身份证/学号"
            class="search-input"
            @keyup.enter.native="handleSearch"
          />
        </el-form-item>
        <el-form-item label="签到状态">
          <el-select
            v-model="searchForm.signStatus"
            placeholder="选择签到状态"
            class="search-select"
            @change="handleSearch"
          >
            <el-option label="全部" value="" />
            <el-option label="已签到（至少1次）" value="signed" />
            <el-option label="未签到（全部缺席）" value="unsigned" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <i class="el-icon-search"></i> 搜索
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">
            <i class="el-icon-refresh-left"></i> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleExport" :disabled="filteredList.length === 0">
        导出Excel
      </el-button>
      <el-button type="primary" plain @click="handleStudentNotice">
        学员通知
      </el-button>
      <el-button type="primary" plain @click="handleRemark" :disabled="selectedRows.length === 0">
        签到备注
      </el-button>
      <el-button type="primary" plain @click="toggleSearch">
        {{ showSearch ? '隐藏搜索' : '显示搜索' }}
      </el-button>
      <el-button type="primary" plain @click="handleRefresh">
        刷新数据
      </el-button>
    </div>

    <!-- 标签切换：正常签到 / 实践预约签到 -->
    <el-tabs
      v-model="activeTab"
      type="card"
      style="margin-bottom: 16px;"
      @tab-click="handleTabChange"
    >
      <el-tab-pane label="正常签到" name="normal"></el-tab-pane>
      <el-tab-pane label="实践预约签到" name="practice"></el-tab-pane>
    </el-tabs>

    <!-- 签到结果表格 -->
    <el-table
      :data="paginatedList"
      border
      stripe
      size="mini"
      style="width: 100%; margin-bottom: 16px;"
      @selection-change="handleSelectionChange"
      v-loading="tableLoading"
      loading-text="数据加载中..."
    >
      <!-- 选择框列 -->
      <el-table-column
        type="selection"
        width="55"
        align="center"
        :visible="visibleColumns.selection"
      ></el-table-column>

      <!-- 固定列：编号、姓名、证件号、电话 -->
      <!-- <el-table-column
        prop="id"
        label="编号"
        width="80"
        align="center"
        :visible="visibleColumns.id"
      ></el-table-column> -->
      <el-table-column
        prop="name"
        label="姓名"
        width="100"
        align="center"
        :visible="visibleColumns.name"
      ></el-table-column>
      <el-table-column
        prop="idCard"
        label="证件编号"
        width="180"
        align="center"
        :visible="visibleColumns.idCard"
      ></el-table-column>
      <el-table-column
        prop="phone"
        label="电话"
        width="130"
        align="center"
        :visible="visibleColumns.phone"
      ></el-table-column>
      <el-table-column
        label="签到次数"
        align="center"
        width="100"
        :visible="visibleColumns.signCount"
      >
        <template #default="scope">
          {{ countSigned(scope.row.signStatuses) }}
        </template>
      </el-table-column>
      <el-table-column
        label="未签到次数"
        align="center"
        width="120"
        :visible="visibleColumns.unsignedCount"
      >
        <template #default="scope">
          {{ countUnsigned(scope.row.signStatuses) }}
        </template>
      </el-table-column>

      <!-- 动态签到列（根据signDates循环） -->
      <el-table-column
        v-for="(date, index) in getSignDates()"
        :key="`sign-col-${index}`"
        :label="date"
        align="center"
        :visible="visibleColumns[`sign_${index}`]"
      >
        <template #default="scope">
          <el-tag
            :type="getTagType(scope.row.signStatuses[index])"
            @click="handleSignDetail(scope.row, index)"
            class="tag-clickable"
          >
            {{ scope.row.signStatuses[index] || '-' }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <!-- 无数据提示 -->
    <div class="no-data" v-if="!tableLoading && filteredList.length === 0">
      <el-empty description="暂无学员签到数据，请检查筛选条件或刷新"></el-empty>
    </div>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pagination.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="filteredList.length"
      size="mini"
      style="text-align: right; margin-top: 8px;"
      v-if="filteredList.length > 0"
    />

    <!-- 1. 签到详情弹窗 -->
    <el-dialog
      title="签到详情"
      :visible.sync="showSignDetailDialog"
      width="400px"
      destroy-on-close
    >
      <div v-if="currentSignRow" class="sign-detail">
        <div class="detail-item">
          <span class="detail-label">学员姓名：</span>
          <span class="detail-value">{{ currentSignRow.name }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">证件编号：</span>
          <span class="detail-value">{{ currentSignRow.idCard }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">签到项：</span>
          <span class="detail-value">{{ currentSignDate }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">签到状态：</span>
          <el-tag :type="getTagType(currentSignStatus)">{{ currentSignStatus || '-' }}</el-tag>
        </div>
        <div class="detail-item">
          <span class="detail-label">签到时间：</span>
          <span class="detail-value">{{ currentSignTime || '未记录' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">签到设备：</span>
          <span class="detail-value">{{ currentSignDevice || '未知' }}</span>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showSignDetailDialog = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 2. 学员备注弹窗 -->
    <el-dialog
      :title="remarkTitle"
      :visible.sync="remarkVisible"
      width="800px"
      @close="resetRemarkForm"
      class="dialog-remark"
    >
      <el-form ref="remarkForm" :model="remarkForm" :rules="remarkRules" label-width="80px">
        <!-- 备注输入框 -->
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="remarkForm.remarks"
            type="textarea"
            :rows="4"
            placeholder="请输入备注内容"
            style="width: 100%"
          ></el-input>
        </el-form-item>

        <!-- 备注历史记录 -->
        <el-table
          :data="remarkHistory"
          border
          style="width: 100%"
          :show-header="true"
        >
          <el-table-column prop="time" label="时间" width="200">
            <template slot-scope="scope">
              {{ scope.row.time }}
            </template>
          </el-table-column>
          <el-table-column prop="operator" label="备注人" width="150">
            <template slot-scope="scope">
              {{ scope.row.operator }}
            </template>
          </el-table-column>
          <el-table-column prop="content" label="备注" min-width="300">
            <template slot-scope="scope">
              {{ scope.row.content }}
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="remarkVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRemark">提交</el-button>
      </div>
    </el-dialog>

    <!-- 3. 学员通知弹窗 -->
    <el-dialog
      title="发送学员通知"
      :visible.sync="noticeDialogVisible"
      width="50%"
      :before-close="handleNoticeDialogClose"
    >
      <el-form :model="noticeForm" ref="noticeForm" :rules="noticeRules">
        <el-form-item label="通知类型" prop="sendTypes">
          <el-checkbox-group v-model="noticeForm.sendTypes">
            <el-checkbox label="0">短信</el-checkbox>
            <el-checkbox label="1">门户</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="通知内容" prop="content">
          <el-input
            type="textarea"
            v-model="noticeForm.content"
            placeholder="请输入通知内容"
            rows="6"
          ></el-input>
        </el-form-item>
        <el-form-item label="发送范围">
          <el-radio-group v-model="noticeForm.range" @change="handleRangeChange">
            <el-radio label="all">所有学员</el-radio>
            <el-radio label="selected">指定选中学员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="noticeForm.range === 'selected'"
          class="selected-users-form-item"
          prop="selectedUsers"
          :rules="[{ required: true, message: '请至少选择一个学员', trigger: 'change' }]"
        >
          <el-select
            v-model="noticeForm.selectedUsers"
            multiple
            placeholder="请输入学员姓名搜索并选择"
            filterable
            remote
            :remote-method="queryUsers"
            :loading="userLoading"
            style="width: 100%;"
            clearable
            @clear="handleSelectClear"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.studentId"
              :label="user.studentName"
              :value="user.studentId"
            >
              <span style="float: left">{{ user.studentName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                身份证号：{{ user.idNumber || '无证件号' }}
              </span>
            </el-option>
            <template #empty>
              <div style="text-align: center; color: #909399;">
                {{ userLoading ? '搜索中...' : '无匹配学员，请更换关键词' }}
              </div>
            </template>
          </el-select>
          <div class="selected-count" v-if="noticeForm.range === 'selected'">
            已选择 {{ noticeForm.selectedUsers.length }} 名学员
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="noticeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitNotice" :loading="noticeLoading">发送</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入接口
import {
  studentNoticeProcess
} from "@/api/training/studentNotice.js";
import {
  listRemarksByParams,
  addRemarks
} from "@/api/training/remarks";
import {
  getClassStudents
} from "@/api/training/ClassStudent";
import {
  selectAllCheckinDetailsByClassId,
} from "@/api/training/ClassCheckin";
import {
  getStudentPracticeCheckIn
} from "@/api/training/practiceClassStudent";

// 日期格式化工具函数
Date.prototype.format = function(fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "H+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

export default {
  name: "SignResultPage",
  data() {
    return {
      // 班级信息（从路由参数获取）
      trainingClassId: "", // 当前班级ID
      trainingClassCode: "", // 当前班级编号
      trainingClassName: "", // 当前班级名称

      // 标签切换状态
      activeTab: "normal", // normal: 正常签到, practice: 实践预约签到
      normalSignList: [], // 正常签到数据
      practiceSignList: [], // 实践预约签到数据
      currentSignList: [], // 当前显示的签到数据

      // 基础配置
      searchForm: {
        name: "",
        phone: "",
        idCard: "",
        signStatus: ""
      },
      showSearch: true,
      tableLoading: false,
      selectedRows: [], // 表格选中行

      // 分页配置
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },

      // 列配置（显隐+排序）
      showColumnDialog: false,
      columnLabels: { // 列名映射
        selection: "选择框",
        id: "编号",
        name: "姓名",
        idCard: "证件编号",
        phone: "电话",
        remark: "备注",
        signCount: "签到次数",
        unsignedCount: "未签到次数"
      },
      visibleColumns: {}, // 控制列显隐（从localStorage读取）
      selectedColumns: [], // 列显隐选择器绑定值

      // 学员通知弹窗配置
      noticeDialogVisible: false,
      noticeLoading: false,
      noticeForm: {
        content: '',
        range: 'all',
        selectedUsers: [],
        sendTypes: []
      },
      noticeRules: {
        sendTypes: [
          { required: true, message: '请选择通知类型', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入通知内容', trigger: 'blur' },
          { max: 500, message: '内容不能超过500个字符', trigger: 'blur' }
        ]
      },
      // 用户选择相关（学员通知用）
      userOptions: [],
      allUsers: [], // 存储所有选中学员数据，用于通知功能
      userLoading: false,

      // 学员备注弹窗配置
      remarkVisible: false, // 控制备注弹窗显示
      remarkTitle: "学员备注", // 弹窗标题
      remarkForm: {
        remarks: "", // 当前备注内容
        foreignId: null, // 关联的学员ID
      },
      remarkTempId: "", // 备注弹窗参数ID（学员ID）
      remarkHistory: [], // 备注历史记录
      remarkRules: {
        remarks: [
          { required: true, message: "请输入备注内容", trigger: "blur" },
          { max: 200, message: "备注内容不能超过200字符", trigger: "blur" }
        ]
      },

      // 签到详情弹窗配置
      showSignDetailDialog: false,
      currentSignRow: null, // 当前查看详情的学员
      currentSignDate: "", // 当前查看的签到项
      currentSignStatus: "", // 当前查看的签到状态
      currentSignTime: "", // 当前查看的签到时间
      currentSignDevice: "" // 当前查看的签到设备
    };
  },
  computed: {
    // 筛选后的列表（处理搜索条件）
    filteredList() {
      return this.currentSignList.filter(row => {
        // 姓名筛选
        if (this.searchForm.name && !row.name.includes(this.searchForm.name)) {
          return false;
        }
        // 手机号筛选
        if (this.searchForm.phone && !row.phone.includes(this.searchForm.phone)) {
          return false;
        }
        // 证件号筛选
        if (this.searchForm.idCard && !row.idCard.includes(this.searchForm.idCard)) {
          return false;
        }
        // 签到状态筛选
        if (this.searchForm.signStatus) {
          const signedCount = this.countSigned(row.signStatuses);
          if (this.searchForm.signStatus === "signed" && signedCount === 0) {
            return false;
          }
          if (this.searchForm.signStatus === "unsigned" && signedCount > 0) {
            return false;
          }
        }
        return true;
      });
    },

    // 分页后的列表
    paginatedList() {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize;
      const end = start + this.pagination.pageSize;
      return this.filteredList.slice(start, end);
    }
  },
  created() {
    // 从路由参数获取当前班级信息
    this.trainingClassId = this.$route.params.classId;
    this.trainingClassCode = this.$route.params.trainingClassCode;
    this.trainingClassName = this.$route.params.className;

    // 初始化列配置
    this.initColumnConfig();
    this.getTrainingList();
  },
  methods: {
    async getTrainingList(){
      this.tableLoading = true;
      try {
        // 获取正常签到数据
        const res = await selectAllCheckinDetailsByClassId({
          trainingClassId: this.trainingClassId
        });
        this.normalSignList = this.formatNormalSignData(res.rows);

        // 获取实践预约签到数据
        const res1 = await getStudentPracticeCheckIn(this.trainingClassId);
        this.practiceSignList = this.formatPracticeSignData(res1.rows);

        // 初始化当前显示的数据
        this.currentSignList = this.normalSignList;
        this.pagination.total = this.currentSignList.length;
      } catch (error) {
        console.error("获取签到数据失败：", error);
        this.$message.error("获取签到数据失败，请重试");
      } finally {
        this.tableLoading = false;
      }
    },

    // 格式化正常签到数据
    formatNormalSignData(rawList) {
      if (!rawList || rawList.length === 0) return [];

      return rawList.map(student => {
        const { studentId, studentName, idNumber, phoneNumber, activityCheckins = [] } = student;

        // 提取签到日期
        const signDates = activityCheckins.map(item => {
          const start = item.checkinStartTime ? new Date(item.checkinStartTime).format("yyyy-MM-dd HH:mm") : "";
          const end = item.checkinEndTime ? new Date(item.checkinEndTime).format("HH:mm") : "";
          return start ? `${start}-${end}` : "未知时段";
        });

        // 提取签到状态
        const signStatuses = activityCheckins.map(item => {
          const statusMap = { 0: "未签到", 1: "已签到", 2: "迟到", 3: "早退" };
          return statusMap[item.checkinStatus] || "未知状态";
        });

        // 提取签到详情
        const signDetails = activityCheckins.map(item => {
          const checkinTime = item.actualCheckinTime
            ? new Date(item.actualCheckinTime).format("yyyy-MM-dd HH:mm:ss")
            : "";
          return {
            time: checkinTime || "未签到",
            device: item.checkinDevice || "未知设备"
          };
        });

        return {
          id: studentId,
          name: studentName,
          idCard: idNumber || "无",
          phone: phoneNumber || "无",
          signDates,
          signStatuses,
          signDetails,
          remark: student.checkinRemark || ""
        };
      });
    },

    // 格式化实践预约签到数据
    formatPracticeSignData(rawList) {
      if (!rawList || rawList.length === 0) return [];

      return rawList.map((student, index) => {
        const {
          studentName,
          idNumber,
          phoneNumber,
          practiceCheckInItems = [], // 实践项目列表（新数据核心字段）
          checkInCount,
          notCheckInCount
        } = student;

        // 1. 提取实践签到项名称（使用practiceName作为签到项标签）
        const signDates = practiceCheckInItems.length > 0
          ? practiceCheckInItems.map(item => item.practiceName || `实践项 ${index + 1}`)
          : ["暂无实践签到项"];

        // 2. 提取实践签到状态（使用checkStatusDesc作为状态描述）
        const signStatuses = practiceCheckInItems.length > 0
          ? practiceCheckInItems.map(item => {
              // 处理状态为"-"的情况（默认视为未签到）
              return item.checkStatusDesc === "-" ? "未签到" : item.checkStatusDesc;
            })
          : ["未签到"];

        // 3. 提取实践签到详情（新数据无时间/设备，用默认值）
        const signDetails = practiceCheckInItems.length > 0
          ? practiceCheckInItems.map(() => ({
              time: "未记录", // 新数据无签到时间，默认显示
              device: "未知设备" // 新数据无设备信息，默认显示
            }))
          : [{ time: "未记录", device: "未知设备" }];

        // 4. 生成学员唯一标识（结合学员信息和实践项ID确保唯一性）
        const firstPracticeId = practiceCheckInItems[0]?.practiceAppointmentId || index;
        const uniqueId = `practice-${firstPracticeId}-${studentName}`;

        return {
          id: uniqueId, // 唯一标识
          name: studentName, // 姓名
          idCard: idNumber || "无", // 证件编号
          phone: phoneNumber || "无", // 电话
          signDates, // 实践签到项名称（表格动态列）
          signStatuses, // 实践签到状态（表格动态列）
          signDetails, // 签到详情（弹窗用）
          checkInCount: checkInCount || 0, // 已签到次数（接口返回）
          notCheckInCount: notCheckInCount || 0, // 未签到次数（接口返回）
          remark: "" // 备注（暂无数据）
        };
      });
    },

    // 初始化列配置
    initColumnConfig() {
      const savedColumns = localStorage.getItem("signPageVisibleColumns");
      if (savedColumns) {
        this.visibleColumns = JSON.parse(savedColumns);
      } else {
        // 默认列显隐配置
        const defaultColumns = {
          selection: true,
          id: true,
          name: true,
          idCard: true,
          phone: true,
          remark: true,
          signCount: true,
          unsignedCount: true
        };
        // 动态添加签到列的显隐配置（根据signDates数量）
        const signDates = this.getSignDates();
        signDates.forEach((_, index) => {
          defaultColumns[`sign_${index}`] = true;
        });
        this.visibleColumns = defaultColumns;
      }
      // 同步到列选择器
      this.selectedColumns = Object.keys(this.visibleColumns).filter(
        key => this.visibleColumns[key]
      );
      // 同步列名映射（添加动态签到列）
      this.syncColumnLabels();
    },

    // 同步列名映射（添加动态签到列）
    syncColumnLabels() {
      const signDates = this.getSignDates();
      signDates.forEach((date, index) => {
        this.columnLabels[`sign_${index}`] = date;
      });
    },

    // 获取签到列的日期列表（取第一条数据的signDates）
    getSignDates() {
      return this.currentSignList.length > 0 ? this.currentSignList[0].signDates : [];
    },

    // 搜索
    handleSearch() {
      this.tableLoading = true;
      // 模拟接口请求延迟
      setTimeout(() => {
        this.pagination.currentPage = 1; // 搜索后重置到第一页
        this.pagination.total = this.filteredList.length;
        this.tableLoading = false;
        this.$message.success(`搜索完成，共找到 ${this.filteredList.length} 条数据`);
      }, 500);
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        name: "",
        phone: "",
        idCard: "",
        signStatus: ""
      };
      this.handleSearch(); // 重置后自动刷新列表
    },

    // 切换搜索区域显示/隐藏
    toggleSearch() {
      this.showSearch = !this.showSearch;
    },

    // 刷新数据
    handleRefresh() {
      this.getTrainingList();
    },

    // 表格选中行变化
    handleSelectionChange(val) {
      this.selectedRows = val;
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1; // 页大小改变后重置到第一页
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
    },

    // 保存列配置
    saveColumnConfig() {
      // 重置所有列显隐为false
      Object.keys(this.visibleColumns).forEach(key => {
        this.visibleColumns[key] = false;
      });
      // 把选中的列设为true
      this.selectedColumns.forEach(key => {
        this.visibleColumns[key] = true;
      });
      // 保存到localStorage
      localStorage.setItem("signPageVisibleColumns", JSON.stringify(this.visibleColumns));
      // 关闭弹窗并提示
      this.showColumnDialog = false;
      this.$message.success("列配置已保存，刷新后生效");
    },

    // Excel导出功能
    handleExport() {
      this.tableLoading = true;
      // 模拟导出延迟
      setTimeout(() => {
        this.tableLoading = false;
        this.$message.success("导出成功");
      }, 800);
    },

    // 标签切换事件
    handleTabChange() {
      this.currentSignList = this.activeTab === "normal"
        ? this.normalSignList
        : this.practiceSignList;

      // 重置分页和搜索
      this.handleReset();
      // 重新初始化列配置以适应新数据
      this.initColumnConfig();
    },

    // ====================== 学员通知功能 ======================
    // 处理学员通知按钮点击
    handleStudentNotice() {
      this.noticeDialogVisible = true;
    },

    // 初始化通知表单
    initNoticeForm() {
      this.noticeForm = {
        content: '',
        range: 'all',
        selectedUsers: [],
        sendTypes: []
      };

      // 加载学员数据
      this.loadStudentsData();

      // 清除表单验证
      this.$nextTick(() => {
        if (this.$refs.noticeForm) {
          this.$refs.noticeForm.clearValidate();
        }
      });
    },

    // 加载学员数据
    async loadStudentsData() {
      try {
        // 调用接口：根据班级ID获取学员列表
        const res = await getClassStudents({
          trainingClassId: this.trainingClassId
        });

        // 统一数据格式
        this.allUsers = res.rows.map(item => {
          const registration = item.registrationDto || {};
          return {
            studentId: registration.studentId || item.studentId,
            studentName: registration.studentName || item.studentName,
            idNumber: registration.idNumber || item.idNumber,
            projectName: registration.projectName || item.projectName
          };
        }).filter(user => user.studentId && user.studentName);

        this.userOptions = [...this.allUsers];

        // 如果当前是"所有学员"模式，更新selectedUsers
        if (this.noticeForm.range === 'all') {
          this.setAllStudents();
        }
      } catch (error) {
        console.error("加载学员数据失败：", error);
        this.$message.error("加载学员数据失败，请稍后重试");
        this.allUsers = [];
        this.userOptions = [];
      }
    },

    // 处理发送范围变化
    handleRangeChange(newRange) {
      // 先加载选中学员数据
      this.loadStudentsData();

      if (newRange === 'all') {
        // 切换到所有选中学员，自动选择全部
        this.setAllStudents();
      } else if (newRange === 'selected') {
        // 切换到指定学员，清空选择
        this.noticeForm.selectedUsers = [];
      }

      // 清除验证状态
      this.$nextTick(() => {
        if (this.$refs.noticeForm) {
          this.$refs.noticeForm.clearValidate('selectedUsers');
        }
      });
    },

    // 设置所有选中学员
    setAllStudents() {
      if (this.allUsers.length > 0) {
        this.noticeForm.selectedUsers = this.allUsers.map(user => user.studentId);
      }
    },

    // 处理选择器清空
    handleSelectClear() {
      this.noticeForm.selectedUsers = [];
    },

    // 关闭通知弹窗
    handleNoticeDialogClose() {
      this.noticeDialogVisible = false;
    },

    // 查询用户（搜索学员）
    async queryUsers(query) {
      if (!query) {
        // 如果搜索为空，显示所有选中学员
        this.userOptions = [...this.allUsers];
        return;
      }

      this.userLoading = true;

      // 模拟搜索延迟
      setTimeout(() => {
        try {
          // 本地搜索过滤（按姓名匹配）
          const filteredUsers = this.allUsers.filter(user =>
            user.studentName && user.studentName.includes(query)
          );
          this.userOptions = filteredUsers;
        } catch (error) {
          console.error("搜索学员失败：", error);
          this.userOptions = [];
        } finally {
          this.userLoading = false;
        }
      }, 300);
    },

    // 提交通知
    submitNotice() {
      this.$refs.noticeForm.validate(async (valid) => {
        if (valid) {
          this.noticeLoading = true;
          try {
            // 整理接口参数
            const noticeParams = {
              sendType: this.noticeForm.range === 'all' ? "1" : "2",
              studentIds: this.noticeForm.range === 'all' ? [] : this.noticeForm.selectedUsers,
              isSms: this.noticeForm.sendTypes.includes('0') ? "1" : "0",
              isPortal: this.noticeForm.sendTypes.includes('1') ? "1" : "0",
              isService: this.noticeForm.sendTypes.includes('2') ? "1" : "0",
              noticeContent: this.noticeForm.content,
              sendTime: new Date().format("yyyy-MM-dd HH:mm:ss"),
              trainingClassId: this.trainingClassId
            };

            // 调用接口
            const res = await studentNoticeProcess(noticeParams);

            if (res.code === 200) {
              this.$message.success("通知发送成功");
              this.noticeDialogVisible = false;
            } else {
              this.$message.error("通知发送失败：" + (res.message || "未知错误"));
            }
          } catch (error) {
            console.error("通知发送接口异常：", error);
            this.$message.error("通知发送失败，请稍后重试");
          } finally {
            this.noticeLoading = false;
          }
        } else {
          this.$message.warning('请完善表单信息');
        }
      });
    },

    // ====================== 学员备注功能 ======================
    // 处理学员备注按钮点击
    async handleRemark() {
      if (this.selectedRows.length === 0) return;

      // 取第一个选中学员的ID
      const studentId = this.selectedRows[0].id;
      this.remarkTempId = studentId;
      this.remarkForm.foreignId = studentId;

      try {
        // 调用接口：获取备注历史
        const res = await listRemarksByParams({
          foreignId: studentId,
          remarkType: "6"
        });

        // 格式化备注历史
        this.remarkHistory = res.rows.map(item => {
          return {
            time: item.createTime,
            operator: item.createBy,
            content: item.remarks
          };
        });

        this.remarkVisible = true;
      } catch (error) {
        console.error("加载学员备注历史失败：", error);
        this.$message.error("加载备注历史失败，请稍后重试");
      }
    },

    // 重置备注表单
    resetRemarkForm() {
      this.$nextTick(function() {
        if (this.$refs.remarkForm) {
          this.$refs.remarkForm.resetFields();
        }
      }.bind(this));
    },

    // 提交备注
    submitRemark() {
      this.$refs["remarkForm"].validate(async function(valid) {
        if (valid) {
          try {
            // 调用接口：提交备注
            const res = await addRemarks({
              foreignId: this.remarkForm.foreignId, // 学员ID
              remarkType: "6", // 学员备注类型
              remarks: this.remarkForm.remarks
            });

            if (res.code === 200) {
              this.$message.success("备注提交成功");
              this.remarkVisible = false;
              this.handleRefresh(); // 刷新列表
            } else {
              this.$message.error("备注提交失败：" + (res.message || "未知错误"));
            }
          } catch (error) {
            console.error("提交学员备注失败：", error);
            this.$message.error("备注提交失败，请稍后重试");
          }
        }
      }.bind(this));
    },

    // ====================== 签到详情功能 ======================
    handleSignDetail(row, index) {
      this.currentSignRow = row;
      this.currentSignDate = row.signDates[index];
      this.currentSignStatus = row.signStatuses[index];
      // 获取签到详情（时间+设备）
      const detail = row.signDetails[index] || {};
      this.currentSignTime = detail.time;
      this.currentSignDevice = detail.device;
      this.showSignDetailDialog = true;
    },

    // ====================== 工具函数 ======================
    // 根据签到状态返回Tag类型
    getTagType(status) {
      switch (status) {
        case "已签到":
          return "success";
        case "未签到":
          return "danger";
        case "请假":
          return "warning";
        case "迟到":
          return "info";
        default:
          return "default";
      }
    },

    // 统计已签到次数
    countSigned(statuses) {
      return statuses.filter(status => status === "已签到").length;
    },

    // 统计未签到次数
    countUnsigned(statuses) {
      return statuses.filter(status => status === "未签到").length;
    }
  },
  // 监听通知弹窗显隐，初始化表单
  watch: {
    noticeDialogVisible(newVal) {
      if (newVal) {
        this.initNoticeForm();
      }
    },
    // 监听当前列表变化，重新初始化列配置
    currentSignList() {
      this.initColumnConfig();
    }
  }
};
</script>

<style scoped>
/* 基础样式 */
.sign-result-page {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
  box-sizing: border-box;
}

/* 顶部信息 */
.top-info {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
  font-size: 14px;
  color: #333;
  flex-wrap: wrap;
}

.class-id, .class-name {
  font-weight: 500;
  padding: 4px 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

/* 搜索区域 */
.search-area {
  margin-bottom: 20px;
  padding: 16px;
  border-radius: 4px;
}

.search-form {
  width: 100%;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.search-input, .search-select {
  width: 180px;
}

/* 操作按钮 */
.operation-buttons {
  margin-bottom: 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.operation-buttons .el-button { padding: 6px 10px; }

/* 表格样式 */
.el-table {
  font-size: 13px;
  margin-bottom: 16px !important;
}

.el-table th {
  background-color: #f5f7fa !important;
  font-weight: 500 !important;
}

.el-tag {
  padding: 2px 6px;
  border-radius: 3px;
  cursor: default;
}

.tag-clickable {
  cursor: pointer;
  transition: all 0.2s;
}

.tag-clickable:hover {
  opacity: 0.8;
}

.remark-input {
  width: 100%;
  border: none;
  padding: 4px 0;
}

.remark-input:focus {
  border-bottom: 1px solid #409eff;
  box-shadow: none;
}

/* 无数据提示 */
.no-data {
  text-align: center;
  padding: 60px 20px;
}

/* 分页 */
.el-pagination {
  margin-top: 16px !important;
}

/* 弹窗样式 */
.dialog-footer {
  text-align: right;
}

/* 学员通知弹窗 */
.empty-notice {
  color: #999;
  font-size: 13px;
  padding: 4px 0;
}

.content-count {
  text-align: right;
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

/* 备注弹窗 */
.remark-user-count {
  color: #666;
  font-size: 13px;
  padding: 4px 0;
}

.dialog-remark .el-textarea {
  width: 100%;
}

/* 签到详情弹窗 */
.sign-detail {
  font-size: 13px;
}

.detail-item {
  margin-bottom: 12px;
  display: flex;
  align-items: flex-start;
}

.detail-label {
  width: 80px;
  color: #666;
  text-align: right;
  margin-right: 12px;
}

.detail-value {
  flex: 1;
  color: #333;
}

/* 已选择学员数量提示 */
.selected-count {
  margin-top: 5px;
  font-size: 12px;
  color: #666;
}

/* 响应式适配 */
@media (max-width: 1200px) {
  .search-input, .search-select {
    width: 150px;
  }
}

@media (max-width: 768px) {
  .top-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .search-input, .search-select {
    width: 100%;
  }

  .operation-buttons {
    justify-content: flex-start;
  }

  .el-table {
    font-size: 12px;
  }

  .el-table-column {
    width: auto !important;
    min-width: 80px;
  }
}
</style>
